import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# 使用pandas分别读取训练数据与测试数据集
digits_train = pd.read_csv('PythonMachineLearningAndPractice/data/section02/12Optdigits/optdigits.tra', header=None)
digtis_test = pd.read_csv('PythonMachineLearningAndPractice/data/section02/12Optdigits/optdigits.tes.txt', header=None)

# 从训练与测试数据集上都分离出64维度的像素特征与1维度的数字目标
X_train = digits_train[np.arange(64)]
y_train = digits_train[64]

X_test = digtis_test[np.arange(64)]
y_test = digtis_test[64]

# 从sklearn.cluster导入KMeans模型
from sklearn.cluster import KMeans

# 初始化KMeans模型，并设置聚类中心数量为10
kmeans = KMeans(n_clusters=10)
kmeans.fit(X_train)
# 逐条 判断每个 测试图像所属的聚类中心
y_predict = kmeans.predict(X_test)

# 从sklearn导入度量函数库metrics
from sklearn import metrics

# 使用ARI进行KMeans聚类性能评估
print(metrics.adjusted_rand_score(y_test, y_predict))



# 利用轮廓系数评价不同类簇数量的K-means聚类实例
from sklearn.metrics import silhouette_score
# from sklearn.cluster import KMeans
# import numpy as np
# import matplotlib.pyplot as plt
# import pandas as pd

# 分割出 3 * 2 = 6个子图，并在1号子图作图
plt.subplot(3, 2, 1)

# 初始化原始数据点
x1 = np.array([1, 2, 3, 1, 5, 6, 5, 5, 6, 7, 8, 9, 7, 9])
x2 = np.array([1, 3, 2, 2, 8, 6, 7, 6 ,7, 1, 2, 1, 1, 3])
# X = np.array(zip(x1, x2)).reshape(len(x1), 2)
X = np.array([[1, 2, 3, 1, 5, 6, 5, 5, 6, 7, 8, 9, 7, 9], [1, 3, 2, 2, 8, 6, 7, 6 ,7, 1, 2, 1, 1, 3]])
# print(X)

plt.xlim([0, 10])
plt.ylim([0 ,10])
plt.title('Instances')
plt.scatter(x1, x2)

colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'b']
markers = ['o', 's', 'D', 'v', '^', 'p', '*', '+']

clusters = [2, 3, 4, 5, 8]
subplot_counter = 1
sc_scores = []
for t in clusters:
    subplot_counter += 1
    plt.subplot(3, 2, subplot_counter)
    kmeas_model = KMeans(n_clusters=t).fit(X)

    for i, l in enumerate(kmeas_model.labels_):
        plt.plot(x1[i], x2[i], color=colors[l], marker=markers[l], ls='None')
        plt.xlim([0, 10])
        plt.ylim([0, 10])
        sc_score = silhouette_score(X, kmeas_model.labels_, metric='euclidean')
        sc_scores.append(sc_score)

        # plt.title('K= %s, silhouette coefficient= %0.03f' %(t, sc_score))

# plt.figure()
# plt.plot(clusters, sc_scores, '*-')
# plt.xlabel('Number of Clusters')
# plt.ylabel('Silhouette Coefficient Score')
# plt.show()
